#include <errno.h>
#ifdef _MSC_VER
#include <WinSock2.h>
#else
#include <sys/socket.h>
#endif

#include "channel_base.h"
#include "retcodes.h"
#include "log.h"

namespace common
{
namespace net
{

CChannelBase::CChannelBase()
{
    fd_ = -1;
    key_ = 0;
}

CChannelBase::~CChannelBase()
{
}

int32_t CChannelBase::Flush()
{
#ifdef _MSC_VER
	int sent = send(fd_, (const char*)output_streams_.ReadBuffer(), output_streams_.Size(), 0);
#else
    int sent = ::send(fd_, output_streams_.ReadBuffer(), output_streams_.Size(), 0);
#endif
	//output_streams_.AddReadBufSize(sent);
    if (sent >= 0)
    {
        output_streams_.AddReadBufSize(sent);
        return sent;
    }
    else if (errno == EWOULDBLOCK)
    {
        LOG_ERROR("default", "send would block : fd:[%d], send[%d]", fd_, sent);
        return ECHANNEL_SEND_BLOCK;
    }
    else
    {
        LOG_ERROR("default", "send sock error : fd:[%d], send[%d]", fd_, sent);
        return ECHANNEL_SEND_ERROR;
    }
}

int32_t CChannelBase::Initialize(uint32_t receive_buffer_capacity, uint32_t send_buffer_capacity)
{
    input_streams_.Initialize(receive_buffer_capacity);
    output_streams_.Initialize(send_buffer_capacity);
    return ::common::SUCCEED;
}

int32_t CChannelBase::Finalize()
{
    input_streams_.Finalize();
    output_streams_.Finalize();
    return ::common::SUCCEED;
}


}
}
